package cn.gemiman.daoyi.module.netty.server.processor;

import cn.gemiman.daoyi.module.netty.contant.NettyRedisKey;
import cn.gemiman.daoyi.module.netty.enums.NettyCmdType;
import cn.gemiman.daoyi.module.netty.enums.NettySendCode;
import cn.gemiman.daoyi.module.netty.model.NettyRecvInfo;
import cn.gemiman.daoyi.module.netty.model.NettySendInfo;
import cn.gemiman.daoyi.module.netty.model.NettySendResult;
import cn.gemiman.daoyi.module.netty.model.NettyUserInfo;
import cn.gemiman.daoyi.module.netty.server.UserChannelCtxMap;
import cn.hutool.core.util.StrUtil;
import io.netty.channel.ChannelHandlerContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
public class PrivateMessageProcessor extends AbstractMessageProcessor<NettyRecvInfo> {

    private final RedisTemplate<String, Object> redisTemplate;

    @Override
    public void process(NettyRecvInfo recvInfo) {
        NettyUserInfo sender = recvInfo.getSender();
        NettyUserInfo receiver = recvInfo.getReceivers().getFirst();
        log.info("接收到消息，发送者:{},接收者:{}，内容:{}", sender.getId(), receiver.getId(), recvInfo.getData());
        try {
            ChannelHandlerContext channelCtx = UserChannelCtxMap.getChannelCtx(receiver.getId(), receiver.getTerminal());
            if (channelCtx != null) {
                // 推送消息到用户
                NettySendInfo<Object> sendInfo = new NettySendInfo<>();
                sendInfo.setCmd(NettyCmdType.PRIVATE_MESSAGE.code());
                sendInfo.setData(recvInfo.getData());
                channelCtx.channel().writeAndFlush(sendInfo);
                // 消息发送成功确认
                sendResult(recvInfo, NettySendCode.SUCCESS);
            } else {
                // 消息推送失败确认
                sendResult(recvInfo, NettySendCode.NOT_FIND_CHANNEL);
                log.error("未找到channel，发送者:{},接收者:{}，内容:{}", sender.getId(), receiver.getId(), recvInfo.getData());
            }
        } catch (Exception e) {
            // 消息推送失败确认
            sendResult(recvInfo, NettySendCode.UNKONW_ERROR);
            log.error("发送异常，发送者:{},接收者:{}，内容:{}", sender.getId(), receiver.getId(), recvInfo.getData(), e);
        }

    }

    private void sendResult(NettyRecvInfo recvInfo, NettySendCode sendCode) {
        if (recvInfo.getSendResult()) {
            NettySendResult<Object> result = new NettySendResult<>();
            result.setSender(recvInfo.getSender());
            result.setReceiver(recvInfo.getReceivers().getFirst());
            result.setCode(sendCode.code());
            result.setData(recvInfo.getData());
            // 推送到结果队列
            String key = StrUtil.join(":", NettyRedisKey.IM_RESULT_PRIVATE_QUEUE,recvInfo.getServiceName());
            redisTemplate.opsForList().rightPush(key, result);
        }
    }
}
